import 'package:flutter/widgets.dart';

/// 转换数据
/// @param json 网络请求回的数据
/// @param key 解析的字段名称
/// @param type 可选参数，定义字段数据类型，注：该参数必须与对象中[key]的类型一致
dynamic safeParse2(Map<String, dynamic> json, String key, [String type]) {
  if (json[key] != null) {
    if (type == null || json[key].runtimeType.toString() == type) {
      return json[key];
    } else if (json[key].runtimeType.toString() != type) {
      String runtimeType = json[key].runtimeType.toString();
      debugPrint(
          'safeParse:{keyName-$key,defineType-$type,runTimeType-$runtimeType}');
      var value = json[key];
      switch (runtimeType) {
        case 'String':
          if (type == 'double') {
            return double.tryParse(value);
          }
          if (type == 'int') {
            return int.tryParse(value);
          }
          break;
        case 'int':
          if (type == 'double') {
            return double.tryParse(value.toString());
          }
          if (type == 'String') {
            return value.toString();
          }
          break;
        case 'double':
          if (type == 'int') {
            return int.tryParse(value.toString());
          }
          if (type == 'String') {
            return value.toString();
          }
          break;
      }
    }
  }

  try {
    if (type != null &&
        type.contains('List') &&
        json[key] != null &&
        json[key] is List) {
      return json[key];
    }
    return null;
  } catch (e) {
    debugPrint('json $key , ${e.toString()}');
  }
  return null;
}
